package cloud.maque.querylist.test;

import org.jasypt.properties.PropertyValueEncryptionUtils;
import org.jasypt.util.text.AES256TextEncryptor;

/**
 * 数据库信息加密工具
 * 链接字符串，用户名和密码都可以加密
 * https://blog.csdn.net/yucaifu1989/article/details/124199659
 */
public final class JasyptEncryptorUtils {



    public static void main(String[] args) {
        //加密
        encode("jdbc:postgresql://192.168.11.121:5432/demo");
        //解密
        decode("w9H2F1s494ndXE4iRWG8lFrZ1eORzzXit7PjIm5pustSU4gT9mbX6HMLTBOoIc583UWoC3hz3hc=");
    }

    /**
     * 加密密码
     */
    private static final String salt = "ZjzsDbEncrypt";

    private static AES256TextEncryptor basicTextEncryptor = new AES256TextEncryptor();

    static {
        basicTextEncryptor.setPassword(salt);
    }

    private JasyptEncryptorUtils() {
    }

    /**
     * 明文加密
     *
     * @param plaintext
     * @return
     */
    public static String encode(String plaintext) {
        System.out.println("明文字符串：" + plaintext);
        String ciphertext = basicTextEncryptor.encrypt(plaintext);
        System.out.println("加密后字符串：" + ciphertext);
        return ciphertext;
    }

    /**
     * 解密
     *
     * @param ciphertext
     * @return
     */
    public static String decode(String ciphertext) {
        System.out.println("加密字符串：" + ciphertext);
        ciphertext = "ENC(" + ciphertext + ")";
        if (PropertyValueEncryptionUtils.isEncryptedValue(ciphertext)) {
            String plaintext = PropertyValueEncryptionUtils.decrypt(ciphertext, basicTextEncryptor);
            System.out.println("解密后的字符串：" + plaintext);
            return plaintext;
        }
        System.out.println("解密失败");
        return "";
    }
}
